package com.archermind.nfc.client.service;

import org.apache.mina.core.session.IoSession;

import com.archermind.nfc.client.transport.MessageHandler;
import com.archermind.nfc.client.transport.MinaClient;
import com.archermind.nfc.common.model.Message;

public abstract class AbstractService implements IService {

	protected IoSession mSession = MinaClient.getInstance().getSession();
	protected MessageHandler mHandler = MinaClient.getInstance()
			.getMessageHandler();

	@Override
	public void sendMessage(Message message) {
		mSession.write(message);
	}

	@Override
	public Message waitMessage(Message message) {
		mHandler.putRequestMessage(message);

		synchronized (message) {
			try {
				message.wait(MAX_WAIT_TIMEOUT);
			} catch (InterruptedException e) {
				mHandler.removeRequestMessage(message.getMessageId());
				return null;
			}
		}

		mHandler.removeRequestMessage(message.getMessageId());

		Message replyMessage = mHandler.getReplyMessage(message.getMessageId());

		return replyMessage;
	}

}
